﻿// ClientSocket.cpp : 实现文件
//

#include "stdafx.h"
#include "FTIRDataAccess.h"
#include "ClientSocket.h"
#include "FFT_Algorithms.h"

unsigned char pDataBuf[5000000];					//接受数据缓存区
void SetResolution(float Resolution);

CClientSocket m_ClientSocket;

// CClientSocket

CClientSocket::CClientSocket()
{
	m_CurAcquireTime = 0;
	m_AcquireDataMode = 0;
	IsHaveNewData = false;
	m_IsConnected = false;
	IsInAcquire = false;
	Datasize=0;

	iDivider = 8;//半波倍频采样 = true;
	m_WaveNumHigh = 11200; m_WaveNumLow = 5800; m_LaserWaveLen = 850.0f;
	pOrgADdata = NULL;
	pPulseTime = NULL;
	pSpeed = NULL;
	pInterferegramBuf = NULL;
	pInterferegramOutputBuf = NULL;
	pSpectrum = NULL;
	ADdataNum = 0; SpeedNum = 0; InterferegramLen = 0;
	m_Resolution = 4.0;
	m_Offset = 0;
	m_Speed = 7.5;
	m_CurAcquireTime = 0;
	
	m_Max_SpectrumLen = 8000;
	pSpectrum = new float[m_Max_SpectrumLen*2];

}

void CClientSocket::SetSpectrumRange(float LowLimit, float HighLimit)
{
	m_WaveNumHigh = HighLimit; m_WaveNumLow = LowLimit;
}

void CClientSocket::SetLaserWaveLength(float LaserWaveLength)
{
	m_LaserWaveLen = LaserWaveLength;
}
void CClientSocket::Command(char com, int data) { //发送指令->cpu0
	char cmd[10] = { 'C', 'C', 'C', 'C' ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,'Z' };
	cmd[4] = com;
	memcpy(cmd + 5, &data, sizeof(data));
	Send(cmd, 10);//网口发送接口函数
	Sleep(100);
}

CClientSocket::~CClientSocket()
{
	if (pOrgADdata) delete pOrgADdata; pOrgADdata = NULL;
	if (pPulseTime) delete pPulseTime; pPulseTime = NULL;
	if (pSpeed) delete pSpeed; pSpeed = NULL;
	if (pInterferegramBuf) delete pInterferegramBuf; pInterferegramBuf = NULL;
	if (pInterferegramOutputBuf) delete pInterferegramOutputBuf; pInterferegramOutputBuf = NULL;
}

// CClientSocket 成员函数
bool CClientSocket::SetFTIRReselution(float Resolution)
{	
	if (Resolution<MaxReselution)  Resolution=MaxReselution;
	if (Resolution>=0.001) m_Resolution = Resolution;
	if (m_Resolution < 0.1) return false;//不支持小于0.1波数分辨率

	int iResolution = WAVE_NUM_4;
	if (Resolution <0.125) {
		iResolution = WAVE_NUM_0_1;
		//0.1波数
	}
	else if (Resolution < 0.25) {
		iResolution = WAVE_NUM_0_125;
		//0.125波数
	}
	else if (Resolution < 0.5) {
		iResolution = WAVE_NUM_0_25;
		//0.25波数
	}
	else if (Resolution < 1) {
		//0.5波数
		iResolution = WAVE_NUM_0_5;
	}
	else if (Resolution < 2) {
		//1波数
		iResolution = WAVE_NUM_1;
	}
	else if (Resolution <4) {
		//2波数
		iResolution = WAVE_NUM_2;
	}
	else if (Resolution < 8) {
		//4波数
		iResolution = WAVE_NUM_4;
	}
	else if (Resolution < 16) {
		//8波数
		iResolution = WAVE_NUM_8;
	}
	else {
		//16波数
		iResolution = WAVE_NUM_16;
	}
	m_ClientSocket.Command(13, iResolution);

	if (pPulseTime) delete pPulseTime; pPulseTime = NULL;
	if (pInterferegramOutputBuf) delete pInterferegramOutputBuf; pInterferegramOutputBuf = NULL;
	if (pInterferegramBuf) delete pInterferegramBuf; pInterferegramBuf = NULL;

	m_OrgDataLength = (int)((4096 *4/ m_Resolution + 1000) * 2)* 48/m_Speed;//双边
	m_ResampleDataLength = (int)((4096*4 / m_Resolution) * 2+1000)* iDivider;//双边
	m_CutDataLength = (int)((4096*4 / m_Resolution) * 2)* iDivider;//双边
	m_PulseLength = (int)((4096*4 / m_Resolution + 1000) * 2);//双边
	if (pOrgADdata) delete pOrgADdata; pOrgADdata = NULL;
	if (pSpeed) delete pSpeed; pSpeed = NULL;
	if (m_AcquireDataMode == 11) {//原始数据
		pOrgADdata = new int[m_OrgDataLength];//双边 10倍采样
	} else if (m_AcquireDataMode == 12) {//速度
		pSpeed = new int[m_PulseLength];
	} else {		
		pInterferegramOutputBuf = new int[m_ResampleDataLength];
		pPulseTime = new int[m_ResampleDataLength];
		if (m_AcquireDataMode < 20)//0.1
			pInterferegramBuf = new int[m_ResampleDataLength];
	}
	
	Sleep(50);
	return true;
}

void CClientSocket::OnConnect(int nErrorCode)
{
	//连接失败程序处理：
	if (0 != nErrorCode)
	{
		switch (nErrorCode)
		{
		case WSAEADDRINUSE:
			AfxMessageBox(_T("The specified address is already in use.指定的地址已在使用中\n"));
			break;
		case WSAEADDRNOTAVAIL:
			AfxMessageBox(_T("The specified address is not available from ")
				_T("the local machine.指定的地址不可用本地机器\n"));
			break;
		case WSAEAFNOSUPPORT:
			AfxMessageBox(_T("Addresses in the specified family cannot be ")
				_T("used with this socket.在指定的家庭中地址不能使用这个套接字。\n"));
			break;
		case WSAECONNREFUSED:
			AfxMessageBox(_T("The attempt to connect was forcefully rejected.试图联系的尝试被强烈拒绝了\n"));
			break;
		case WSAEDESTADDRREQ:
			AfxMessageBox(_T("A destination address is required.需要一个目标地址\n"));
			break;
		case WSAEFAULT:
			AfxMessageBox(_T("The lpSockAddrLen argument is incorrect.地址长度不对\n"));
			break;
		case WSAEINVAL:
			AfxMessageBox(_T("The socket is already bound to an address.套接字已经绑定到一个地址。\n"));
			break;
		case WSAEISCONN:
			AfxMessageBox(_T("The socket is already connected.套接字已经连接了。\n"));
			break;
		case WSAEMFILE:
			AfxMessageBox(_T("No more file descriptors are available.没有更多的文件描述符可用\n"));
			break;
		case WSAENETUNREACH:
			AfxMessageBox(_T("The network cannot be reached from this host ")
				_T("at this time.\n"));
			break;
		case WSAENOBUFS:
			AfxMessageBox(_T("No buffer space is available. The socket ")
				_T("cannot be connected.没有缓冲空间可用。套接字无法连接\n"));
			break;
		case WSAENOTCONN:
			AfxMessageBox(_T("The socket is not connected.套接字没有连接。\n"));
			break;
		case WSAENOTSOCK:
			AfxMessageBox(_T("The descriptor is a file, not a socket.描述符是一个文件，而不是一个套接字\n"));
			break;
		case WSAETIMEDOUT:
			AfxMessageBox(_T("The attempt to connect timed out without ")
				_T("establishing a connection. \n"));
			break;
		default:
			TCHAR szError[256];
			_stprintf_s(szError, _T("OnConnect error: %d"), nErrorCode);
			AfxMessageBox(szError);
			break;
		}
		AfxMessageBox(_T("Please close the application"));
	}
	m_IsConnected = true;
	CAsyncSocket::OnConnect(nErrorCode);
}

//pData,pTime 前面至少两个数据，后面至少3个数据，
//dTime位于*pTime,*(pTime+1)之间（*pTime<=dTime<*(pTime+1)）
int AkimaIntercpolation(int *pData, int *pTime, int dTime)
{
	double Mk, Mka1,Mka2, Mks1, Mks2,tk,tka1,Value,delta;
	Mk = (double)(*(pData + 1) - *(pData)) / (*(pTime + 1) - *(pTime));
	Mka1 = (double)(*(pData + 2) - *(pData+1)) / (*(pTime + 2) - *(pTime+1));
	Mka2 = (double)(*(pData + 3) - *(pData + 2)) / (*(pTime + 3) - *(pTime + 2));
	Mks1 = (double)(*(pData) - *(pData-1)) / (*(pTime) - *(pTime-1)); 
	Mks2 = (double)(*(pData -1) - *(pData-2)) / (*(pTime -1) - *(pTime-2));
	tk = (fabs(Mka1 - Mk)*Mks1 + fabs(Mks1 - Mks2)*Mk) / max(0.01,(fabs(Mka1 - Mk) + fabs(Mks1 - Mks2)));
	tka1 = (fabs(Mka2 - Mka1)*Mk + fabs(Mk - Mks1)*Mka1) / max(0.01,(fabs(Mka2 - Mka1) + fabs(Mk - Mks1)));
	double c0, c1, c2, c3;
	c0 = *pData;
	c1 = tk;
	c2 = (3 * Mk - 2 * tk - tka1) / (*(pTime + 1) - *(pTime));
	c3 = (tk + tka1-2*Mk) / ((*(pTime + 1) - *(pTime))*(*(pTime + 1) - *(pTime)));
	delta = dTime - *pTime;
	Value = c0 + c1*delta + c2*delta*delta + c3*delta*delta*delta;
	int iValue;
	iValue=(int)Value;
	if ((iValue < -18588608) || (iValue > 18588608)) {
		Value = Value;
	}
	return iValue;
}

void CClientSocket::OnReceive(int nErrorCode)
{
	int nRead;
	nRead = 0;
	if (Datasize < 5000000 - 400000) {
		nRead=Receive(pDataBuf + Datasize, 400000);//接收数据到pDataBuf
		switch (nRead)
		{
		case 0:
			Close();
			break;
		case SOCKET_ERROR:
			if (GetLastError() != WSAEWOULDBLOCK)
			{
				AfxMessageBox(_T("Error occurred"));
				Close();
			}
			break;
		default:
			Datasize = Datasize + nRead;
			break;
		}
	}
	else {
		AfxMessageBox(_T("缓存区太小！"));
	}

	int ADdataNumByte = (int)(pDataBuf[12]) + (int)(pDataBuf[13]) * 256 + (int)(pDataBuf[14]) * 256 * 256 + (int)(pDataBuf[15]) * 256 * 256 * 256;
	int SpeeddataNumByte = (int)(pDataBuf[16]) + (int)(pDataBuf[17]) * 256 + (int)(pDataBuf[18]) * 256 * 256 + (int)(pDataBuf[19]) * 256 * 256 * 256;
	int Direction = pDataBuf[4];
	int ReceieveBytelength = SpeeddataNumByte + ADdataNumByte * 2 + 28;
	if ((pDataBuf[0] == 'A') && (pDataBuf[1] == 'A') && (pDataBuf[2] == 'A') && (pDataBuf[3] == 'A'))
	{
		if ((pDataBuf[ReceieveBytelength - 4] == 'T') && (pDataBuf[ReceieveBytelength - 3] == 'a') && (pDataBuf[ReceieveBytelength - 2] == 'i') && (pDataBuf[ReceieveBytelength - 1] == 'l'))
		{
			ADdataNum = ADdataNumByte / 4;
			SpeedNum = SpeeddataNumByte / 4 - 1;
			if ((ADdataNum <= m_OrgDataLength) && (ADdataNum >= m_OrgDataLength - 20000)) {//太长和太短都意会着扫描不正常
			//{
				if (Direction == 0) {
					//反向数据必须处理（颠倒和取负值）以便和正向一致，
					int *pSpeedTime, *pADTime, *pAD, i, ibuf;
					pAD = (int *)(pDataBuf + 24);
					pADTime = (int *)(pDataBuf + 24 + ADdataNumByte);
					for (i = 0; i < ADdataNum / 2; i++) {
						//首位交换AD数据
						ibuf = *(pAD + i);
						*(pAD + i) = *(pAD + (ADdataNum - 1 - i));
						*(pAD + (ADdataNum - 1 - i)) = ibuf;
						//首位交换AD时间数据
						ibuf = *(pADTime + i);
						*(pADTime + i) = *(pADTime + (ADdataNum - 1 - i));
						*(pADTime + (ADdataNum - 1 - i)) = ibuf;
					}
					pSpeedTime = (int *)(pDataBuf + 24 + ADdataNumByte * 2);
					for (i = 0; i < SpeedNum / 2; i++) {
						//首位交换脉冲时间数据
						ibuf = *(pSpeedTime + i);
						*(pAD + i) = *(pSpeedTime + (SpeedNum - 1 - i));
						*(pSpeedTime + (SpeedNum - 1 - i)) = ibuf;
					}
				}

				int SampleNum;
				if ((m_AcquireDataMode != 11) && (m_AcquireDataMode != 12)) {
					if ((iDivider == 1) || (m_AcquireDataMode == 13)) {
						int *pSpeedTime;
						pSpeedTime = (int *)(pDataBuf + 24 + ADdataNumByte * 2);
						for (int i = 0; i < SpeedNum; i++)
							pPulseTime[i] = pSpeedTime[i];
						SampleNum = SpeedNum;
					}
					else {
						int *pSpeedTime;
						pSpeedTime = (int *)(pDataBuf + 24 + ADdataNumByte * 2);
						for (int i = 0; i < SpeedNum; i++)
							pPulseTime[i*iDivider] = pSpeedTime[i];
						for (int i = 0; i < SpeedNum - 1; i++)
							for (int j = 1; j < iDivider; j++) {
								pPulseTime[i * iDivider + j] = pPulseTime[i * iDivider] + (pPulseTime[(i + 1)*iDivider] - pPulseTime[i*iDivider])*j / iDivider;
							}
						SampleNum = (SpeedNum - 1)*iDivider;
					}
				}
				switch (m_AcquireDataMode) {
				case 11:
				{
					//接收原始干涉数据
					//memcpy(pOrgADdata, pDataBuf + 24, ADdataNumByte);
					int *pOrg, *pAD;
					//int MaxValue, MinValue, MaxIndex, MinIndex;
					int Value;
					ADdataNum = min(m_OrgDataLength, ADdataNum);
					pOrg = pOrgADdata;
					pAD = (int *)(pDataBuf + 24);
					for (int i = 0; i <ADdataNum; i++) {
						Value = *pAD;
						*pOrg = Value / 100;
						pOrg++; pAD++;
					}
					IsHaveNewData = true;
				}
				m_CurAcquireTime = 1;
				break;
				case 12:
				{
					//转换成速度图
					int *pSpeedTime;
					pSpeedTime = (int *)(pDataBuf + 24 + ADdataNumByte * 2);
					for (int i = 0; i < SpeedNum - 1; i++)
					{
						pSpeed[i] = pSpeedTime[i + 1] - pSpeedTime[i];
					}
				}
				m_CurAcquireTime = 1;
				IsHaveNewData = true;
				break;
				case 13:
				{
					//转换成干涉图，一个波长采一次,不移动到中间，用于校正干涉图偏移
					int *pADTime, *pAD;
					pAD = (int *)(pDataBuf + 24);
					pADTime = (int *)(pDataBuf + 24 + ADdataNumByte);

					memset(pInterferegramOutputBuf, 0, m_ResampleDataLength * 4);
					int Value;
					int ADst = 3;
					int PuslseSt = 0;
					InterferegramLen = 0;
					if ((pPulseTime[100] - pPulseTime[99]) > 0) {//递增时序
						while ((pPulseTime[PuslseSt] <= pADTime[ADst]) && (PuslseSt < SampleNum)) {
							PuslseSt++;//保证起始的第一个脉冲时标大于第一个AD时标
						}
						while ((PuslseSt < SampleNum - 2) && (ADst < ADdataNum - 3) && (InterferegramLen < m_ResampleDataLength)) {
							while ((pPulseTime[PuslseSt] >= pADTime[ADst]) && (ADst < ADdataNum - 3)) ADst++;//找到脉冲时标后的第一个AD
							ADst--;
							while ((pPulseTime[PuslseSt] < pADTime[ADst]) && (ADst < ADdataNum - 3)) ADst--;//找到脉冲时标后的第一个AD
							{
								pInterferegramOutputBuf[InterferegramLen] = (int)AkimaIntercpolation(pAD + ADst, pADTime + ADst, pPulseTime[PuslseSt]);// pAD[ADst];
								Value = pInterferegramOutputBuf[InterferegramLen];
								InterferegramLen++;
							}
							PuslseSt++;
						}
					}
					else {				//递减时序
						while ((pPulseTime[PuslseSt] >= pADTime[ADst]) && (PuslseSt < SampleNum)) PuslseSt++;//保证起始的第一个脉冲时标小于第一个AD时标
						while ((PuslseSt < SampleNum - 2) && (ADst < ADdataNum - 3) && (InterferegramLen < m_ResampleDataLength)) {
							while ((pPulseTime[PuslseSt] <= pADTime[ADst]) && (ADst < ADdataNum - 3)) ADst++;//找到脉冲时标后的第一个AD
							ADst--;
							while ((pPulseTime[PuslseSt] > pADTime[ADst]) && (ADst < ADdataNum - 3)) ADst--;//找到脉冲时标后的第一个AD
							{
								pInterferegramOutputBuf[InterferegramLen] = (int)AkimaIntercpolation(pAD + ADst, pADTime + ADst, pPulseTime[PuslseSt]);// pAD[ADst];
								Value = pInterferegramOutputBuf[InterferegramLen];
								InterferegramLen++;
							}
							PuslseSt++;
						}
					}
				}
				m_CurAcquireTime = 1;
				IsHaveNewData = true;
				break;
				case 0:case 1:
				{
					//转换成干涉图,并移到中间，1：进一步转换成光谱图
					int *pADTime, *pAD;
					pAD = (int *)(pDataBuf + 24);
					pADTime = (int *)(pDataBuf + 24 + ADdataNumByte);
					int ADst = 3;
					int PuslseSt = 0;
					int MaxValue, MaxIndex, Value;
					InterferegramLen = 0; MaxValue = -100000; MaxIndex = 0;
					if ((pPulseTime[100] - pPulseTime[99]) > 0) {//递增时序
						while ((pPulseTime[PuslseSt] <= pADTime[ADst]) && (PuslseSt < SampleNum)) {
							PuslseSt++;//保证起始的第一个脉冲时标大于第一个AD时标
						}
						while ((PuslseSt < SampleNum - 2) && (ADst < ADdataNum - 3) && (InterferegramLen < m_ResampleDataLength)) {
							while ((pPulseTime[PuslseSt] >= pADTime[ADst]) && (ADst < ADdataNum - 3)) ADst++;//找到脉冲时标后的第一个AD
							ADst--;
							while ((pPulseTime[PuslseSt] < pADTime[ADst]) && (ADst < ADdataNum - 3)) ADst--;//找到脉冲时标后的第一个AD
							{
								Value = (int)AkimaIntercpolation(pAD + ADst, pADTime + ADst, pPulseTime[PuslseSt]);// pAD[ADst];
								pInterferegramBuf[InterferegramLen] = Value;
								if (Value > MaxValue) {
									MaxValue = Value;
									MaxIndex = InterferegramLen;
								}
								InterferegramLen++;
							}
							PuslseSt++;
						}
					}
					else {				//递减时序
						while ((pPulseTime[PuslseSt] >= pADTime[ADst]) && (PuslseSt < SampleNum)) PuslseSt++;//保证起始的第一个脉冲时标小于第一个AD时标
						while ((PuslseSt < SampleNum - 2) && (ADst < ADdataNum - 3) && (InterferegramLen < m_ResampleDataLength)) {
							while ((pPulseTime[PuslseSt] <= pADTime[ADst]) && (ADst < ADdataNum - 3)) ADst++;//找到脉冲时标后的第一个AD
							ADst--;
							while ((pPulseTime[PuslseSt] > pADTime[ADst]) && (ADst < ADdataNum - 3)) ADst--;//找到脉冲时标后的第一个AD
							{
								Value = (int)AkimaIntercpolation(pAD + ADst, pADTime + ADst, pPulseTime[PuslseSt]);// pAD[ADst];
								pInterferegramBuf[InterferegramLen] = Value;
								if (Value > MaxValue) {
									MaxValue = Value;
									MaxIndex = InterferegramLen;
								}
								InterferegramLen++;
							}
							PuslseSt++;
						}
					}
					//移到中间
					memset(pInterferegramOutputBuf, 0, m_CutDataLength * 4);
					int St, Ed, Std;
					if (MaxIndex <= m_CutDataLength / 2) {
						St = 0;
						Std = m_CutDataLength / 2 - MaxIndex;
					}
					else {
						St = MaxIndex - m_CutDataLength / 2;
						Std = 0;
					}
					if (InterferegramLen - MaxIndex > m_CutDataLength / 2) {
						Ed = MaxIndex + m_CutDataLength / 2;
					}
					else {
						Ed = InterferegramLen;
					}
					for (int i = St; i < Ed; i++)
						pInterferegramOutputBuf[(i - St) + Std] = pInterferegramBuf[i];

					InterferegramLen = m_CutDataLength;
				}
				if (m_AcquireDataMode == 1) {		//转换成光谱
					CacuSpectrum();					//光谱图进行积分
				}
				else {
					m_CurAcquireTime = 1;
				}
				IsHaveNewData = true;
				break;
				}
			}
			//清空缓存区
			memset(pDataBuf, 0, ReceieveBytelength);
			Datasize = 0;
		}
		if (Datasize >= ReceieveBytelength - 1)	Datasize = 0;
	} else Datasize = 0;
	CAsyncSocket::OnReceive(nErrorCode);
}

bool CClientSocket::StartCotinueAcquireOrginalData()
{
	if (IsInAcquire) {
		StopAcquire();
		for (int i = 0; i < 10; i++) {
			MSG msg;
			while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
			{
				::TranslateMessage(&msg);
				::DispatchMessage(&msg);
			}
			Sleep(30);
		}
	}
	IsInAcquire = true;
	Command(11, 0);//网口发送接口函数,开始采集
	return true;
}

bool CClientSocket::StopAcquire()
{
	Command(12, 0);//网口发送接口函数,停止采集
	IsInAcquire = false;
	return true;
}

void CClientSocket::OnClose(int nErrorCode)
{
	m_IsConnected = false;
	CAsyncSocket::OnClose(nErrorCode);
}

int CClientSocket::CacuSpectrum(void)
{
	int TransformLength,i;
	TransformLength = 2048 *(int)(16 / m_Resolution+0.99)*iDivider;
	//提取双边干涉图
	double* pdbRawData;
	pdbRawData = new double[TransformLength];
	for (i=0;i< TransformLength;i++)
		pdbRawData[i]= pInterferegramOutputBuf[i + (InterferegramLen / 2-TransformLength/2)] ;

	FFT_Apodization(pdbRawData, TransformLength, "triangle");
	double* pdbFFT_Re = new double[TransformLength];//变换后的实部
	double* pdbFFT_Im = new double[TransformLength];//变换后的虚部
	double* pdbFFTPowerSpec = new double[TransformLength];//变换后的功率谱
	//进行FFT变换
	FFT_radix2(pdbRawData, TransformLength, pdbFFT_Re, pdbFFT_Im);
	//计算功率谱
	double dbFactorForPwerSpec = 1.0 / 16384.0;
	for (i = 0; i < TransformLength; i++)
	{
		pdbFFTPowerSpec[i] = sqrt(pdbFFT_Re[i] * pdbFFT_Re[i] + pdbFFT_Im[i] * pdbFFT_Im[i]) * dbFactorForPwerSpec;
	}
	//将功率谱左右对叠
	int iFFTPowerSpecDotCount = (TransformLength >> 1);
	for (i = 0; i < iFFTPowerSpecDotCount; i++)
	{
		pdbFFTPowerSpec[i] = (pdbFFTPowerSpec[i] + pdbFFTPowerSpec[TransformLength - i - 1]) / 2;
	}
	//提取出光谱
	double* pdbFinalSpecX = new double[iFFTPowerSpecDotCount];
	double* pdbFinalSpecY = new double[iFFTPowerSpecDotCount];
	
	int iFinalSpecDotCount = FFT_ExtractSpecFromFFTResult(pdbFFTPowerSpec, iFFTPowerSpecDotCount, m_LaserWaveLen, m_WaveNumLow, m_WaveNumHigh, iDivider, pdbFinalSpecX, pdbFinalSpecY);

	if (m_Max_SpectrumLen < iFFTPowerSpecDotCount) {
		MessageBox(NULL, _T("缓冲区不够！"), _T("警告"), IDOK);
		return 0;
	}
	else {
		if (m_ClientSocket.m_CurAcquireTime == 0) {
			for (i = 0; i < iFinalSpecDotCount; i++) {
				pSpectrum[i * 2] = (float)pdbFinalSpecX[i];
				pSpectrum[i * 2 + 1] = (float)pdbFinalSpecY[i]/100;
			}
		}
		else {
			for (i = 0; i < iFinalSpecDotCount; i++) {
				pSpectrum[i * 2 + 1] += (float)pdbFinalSpecY[i]/100;
			}
		}
		m_CurAcquireTime++;
	}
	delete pdbFinalSpecY; delete pdbFinalSpecX;
	delete pdbFFTPowerSpec;
	delete pdbFFT_Re; delete pdbFFT_Im;
	delete pdbRawData;
	m_SpectrumLen = iFinalSpecDotCount;
	return 1;
}

bool ConnectHardware(int nFild0, int nFild1,int nFild2,int nFild3,int port)
{
	BOOL Sucess;
	Sucess = m_ClientSocket.Create();
	if (!Sucess) {
		DWORD Error = GetLastError();
		return false;
	}
	CString sIP;
	sIP.Format(_T("%d.%d.%d.%d"), nFild0, nFild1, nFild2, nFild3);
	Sucess = m_ClientSocket.Connect(sIP, port);
	if (!Sucess) {
		DWORD Error = GetLastError();
		return false;
	}
	int WaitTimes = 0;
	do {
		MSG msg;
		while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			::TranslateMessage(&msg);
			::DispatchMessage(&msg);
		}
		Sleep(50);
		WaitTimes++;
	} while ((WaitTimes < 100) && (m_ClientSocket.m_IsConnected == false));
	return m_ClientSocket.m_IsConnected;
}

bool DisConnectHardware()
{
	m_ClientSocket.Close();
	return true;
}

int GetOrginalData(float *pADDataOut,int *pADTimeOut,int &MaxDataLengtn)
{
	if (m_ClientSocket.m_AcquireDataMode != 11) {
		AfxMessageBox(L"不在原始干涉图采集模式");
		return false;
	}
	if (m_ClientSocket.IsHaveNewData==false) return 0;
	if (MaxDataLengtn < m_ClientSocket.ADdataNum) {
		MessageBox(NULL,_T("输出缓冲区不够！"),_T("警告"),IDOK);
		return false;
	}
	for (int i = 0; i < m_ClientSocket.ADdataNum; i++) pADDataOut[i] = (float)m_ClientSocket.pOrgADdata[i];
	m_ClientSocket.IsHaveNewData = false;
	MaxDataLengtn = m_ClientSocket.ADdataNum;
	return 1;
}

int GetInterferegram(float *pInterferegramOut, int &MaxDataLengtn)
{
	if ((m_ClientSocket.m_AcquireDataMode>1) && (m_ClientSocket.m_AcquireDataMode != 13)) {
		AfxMessageBox(L"不在干涉图采集模式");
		return false;
	}
	if (m_ClientSocket.IsHaveNewData == false) return 0;
	if (MaxDataLengtn < m_ClientSocket.InterferegramLen) {
		MessageBox(NULL, _T("输出缓冲区不够！"), _T("警告"), IDOK);
		return false;
	}
	for (int i = 0; i < m_ClientSocket.InterferegramLen; i++) pInterferegramOut[i] = m_ClientSocket.pInterferegramOutputBuf[i]*2.4f/8388608.0f;
	m_ClientSocket.IsHaveNewData = false;
	MaxDataLengtn = m_ClientSocket.InterferegramLen;
	return 1;
}

void SetParameter(float dbLaserWaveLen, float dbWaveNumLow, float dbWaveNumHigh)
{
	m_ClientSocket.m_WaveNumHigh= dbWaveNumHigh;
	m_ClientSocket.m_WaveNumLow= dbWaveNumLow;
	m_ClientSocket.m_LaserWaveLen= dbLaserWaveLen;
}

int GetSpectrum(float *Spectrum, int &MaxDataLengtn)
{
	if (m_ClientSocket.m_AcquireDataMode != 1) {
		AfxMessageBox(L"不在光谱图采集模式");
		return false;
	}
	if (m_ClientSocket.m_CurAcquireTime < 1) return 0;
	if (m_ClientSocket.IsHaveNewData == false) return 0;
	for (int i = 0; i < min(MaxDataLengtn, m_ClientSocket.m_SpectrumLen); i++)
	{
		Spectrum[i*2+1] = m_ClientSocket.pSpectrum[i*2+1] / m_ClientSocket.m_CurAcquireTime;
		Spectrum[i*2] = m_ClientSocket.pSpectrum[i*2];
	}
	m_ClientSocket.IsHaveNewData = false;
	MaxDataLengtn = min(MaxDataLengtn , m_ClientSocket.m_SpectrumLen*2);
	return min(MaxDataLengtn/2, m_ClientSocket.m_SpectrumLen);
}

int GetSpeed(float *pSpeedOut, int &MaxDataLengtn)
{
	if (m_ClientSocket.m_AcquireDataMode != 12) {
		AfxMessageBox(L"不在速度图采集模式");
		return false;
	}
	if (m_ClientSocket.IsHaveNewData==false) return 0;
	if (MaxDataLengtn < m_ClientSocket.SpeedNum) {
		MessageBox(NULL, _T("输出缓冲区不够！"), _T("警告"), IDOK);
		return false;
	}
	for (int i = 0; i < m_ClientSocket.SpeedNum; i++) pSpeedOut[i] = 100000000.0f/max(100,(float)m_ClientSocket.pSpeed[i]);
	m_ClientSocket.IsHaveNewData = false;
	MaxDataLengtn=m_ClientSocket.SpeedNum;
	return 1;
}

void SetResolution(float Resolution)
{
	m_ClientSocket.SetFTIRReselution(Resolution);
}

/******************************************************************************
* 函数：SetMoveSpeed
* 功能：设置动镜速度档位
* @param: 可取值2,3,4,5，对应动镜速度 40000,30000,10000,7500
* 返回值 : 无
*******************************************************************************/
void SetMoveSpeed(float Speed)//cm/s
{
	int NewSpeed;
	if (Speed > 9.492f) {
		//40K
		m_ClientSocket.m_Speed = 40;
		NewSpeed = 2;
	}
	else if (Speed > 4.746f) {
		//20K
		m_ClientSocket.m_Speed = 10;
		NewSpeed = 3;
	}
	else if (Speed >2.7685f) {
		//10K
		m_ClientSocket.m_Speed = 10;
		NewSpeed = 4;
	}
	else {//if (Speed >1.8f) {
		//7.5K
		m_ClientSocket.m_Speed = 7.5;
		NewSpeed = 5;
	}
	/*else {
		//5K
		m_ClientSocket.m_Speed = 5.0;
		NewSpeed = 6;
	}*/
	m_ClientSocket.Command(14, NewSpeed);//网口发送接口函数,开始采集
//	Sleep(50);
}

bool IsHardwareConnected(void)
{
	if (m_ClientSocket.m_IsConnected == false) return false;
	else {
		return true;
	}
}

bool HaveNewData(void)
{
	return m_ClientSocket.IsHaveNewData;
}

//AcquireDataMode 11:原始数据,  12:速度图， 13:干涉图(不移动至中间)
//0:干涉图并移到中间,1:采光谱图
void BeginDataAcquire(int AcquireDataMode)
{
	if (AcquireDataMode != m_ClientSocket.m_AcquireDataMode) {
		m_ClientSocket.m_AcquireDataMode = AcquireDataMode;
		m_ClientSocket.SetFTIRReselution();//未分配空间
	} else m_ClientSocket.m_AcquireDataMode = AcquireDataMode;
	m_ClientSocket.m_CurAcquireTime = 0;
/*	if (AcquireDataMode = 1) {//采集光谱，清除累加区域
		m_ClientSocket.m_CurAcquireTime = 0;
		memset(m_ClientSocket.pSpectrum, 0, m_ClientSocket.m_Max_SpectrumLen * 8);
	}*/
	m_ClientSocket.IsHaveNewData = false;
	m_ClientSocket.StartCotinueAcquireOrginalData();
}

void StopDataAcquire(void)
{
	m_ClientSocket.Command(12, 0);
}

/******************************************************************************
* 函数：SetMoveOffset
* 功能：设置动镜移动偏移量，正值正向偏移，负值反向偏移
* @param: 偏移量
* 返回值 : 无
*******************************************************************************/
void SetZeroOffset(int Offset)
{
	m_ClientSocket.m_Offset = Offset;
	m_ClientSocket.Command(15, Offset);
//	Sleep(50);
}

void SetPhaseX(int PhaseX)
{
	m_ClientSocket.Command(16, PhaseX);
//	Sleep(50);
}

void SetPhaseY(int PhaseY)
{
	m_ClientSocket.Command(17, PhaseY);
//	Sleep(50);
}

void StopMove() { //PC停止动镜移动
	m_ClientSocket.Command(18, 0);
}

void StartMove() { //PC启动动镜移动
	m_ClientSocket.Command(19, 0);
}

void TurnOffIr() { //红外光源休眠
	m_ClientSocket.Command(20, 0);
}

void TurnOnIr() { //红外光源唤醒
	m_ClientSocket.Command(20, 1);
}

void SetIrBright(int data) { //设置红外光源亮度  data >= 0 ，硬件没有驱动
	m_ClientSocket.Command(21, data);
}

void TurnOffLaser() { //激光光源休眠
	m_ClientSocket.Command(22, 0);
}

void TurnOnLaser() { // 激光光源唤醒
	m_ClientSocket.Command(22, 1);
}

void SetrLaserBright(int data) { //设置激光光源亮度  data >= 0 ，硬件没有驱动
	m_ClientSocket.Command(23, data);
}

void SetAcquireDirection(int data) { //PC设置采集方向 0:双向 1:正向  2:反向
	m_ClientSocket.Command(24, data);
}

void SetFastMoveDirection(int data) { //PC设置动镜快扫方向 0:双向 1:正向  2:反向
	m_ClientSocket.Command(25, data);
}

void EnablePhaseCorrect(bool Enable) { //PC设置是否相位校正  0:不进行   1:进行
	int data;
	if (Enable) data = 1; else data = 0;
	m_ClientSocket.Command(26, data);
}

void SetGain(float Gain) {  //设置红外光谱调理电路的放大比例 65535 >= data >= 0
	int data;
	data =(int)Gain * 100;
	m_ClientSocket.Command(27, data);
}

void SetAcqMode(int data) {  //设置采集模式 0：连续刺激，采样率取决于AD芯片 1：定时采集，由FPGA定时采集  2：触发采集，由LF398存储电平后采集
	m_ClientSocket.Command(28, data);
}

bool HardwareInit(int nFild0, int nFild1, int nFild2, int nFild3, int port)
{
	ConnectHardware(nFild0, nFild1, nFild2, nFild3, port);
	if (m_ClientSocket.m_IsConnected) {
		Sleep(100);
		//设置默认值
		//TurnOffLaser(false);
		SetFastMoveDirection(0); SetAcquireDirection(2);//SetFastMoveDirection(1);
		//SetPhaseX(0); SetPhaseY(0); EnablePhaseCorrect(1); 
		//SetZeroOffset(0); 
		SetMoveSpeed(3.16f); //StopMove(false);
		SetResolution(4.0f);
		//LowerLight(false); SetGain(1.0f);
	}
	int data;
	data = 10;
	Sleep(100);
	m_ClientSocket.Command(29, data);
	
//	m_ClientSocket.Command(36, data)

	/*m_ClientSocket.Command(33, data);
	m_ClientSocket.Command(34, data);
	data = 100;
	m_ClientSocket.Command(35, data);
	m_ClientSocket.Command(36, data);*/
	return true;
}

bool HardwareExit()
{
	DisConnectHardware();
	return true;
}

float GetCurrrntReselution(void)
{
	return m_ClientSocket.m_Resolution;
}

int GetCurrentOffset(void)
{
	return m_ClientSocket.m_Offset;
}